package com.xh.hongrpc.loadbalancer;

import com.xh.hongrpc.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class ConsistentHashLoadBalancer implements LoadBalancer{

    //一致性哈希环，存放虚拟节点
    private final TreeMap<Integer, ServiceMetaInfo> virtualNodes = new TreeMap<>();
    //虚拟节点数
    private static final int VIRTUAL_NODE_SIZE = 100;
    @Override
    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceMetaInfoList) {
        if (serviceMetaInfoList.isEmpty())
            return null;

        //构建虚拟节点
        for (ServiceMetaInfo serviceMetaInfo : serviceMetaInfoList){
            for (int i = 0; i < VIRTUAL_NODE_SIZE; i++){
                int  hash = getHash(serviceMetaInfo.getServiceAddress()  + "#" + i);
                virtualNodes.put(hash, serviceMetaInfo);
            }
        }

        //获取请求参数的哈希值
        int hash = getHash(requestParams);
        //查找哈希环中，第一个大于或等于指定 hash 的键值对
        Map.Entry<Integer, ServiceMetaInfo> entry = virtualNodes.ceilingEntry(hash);
        if (entry == null){
            //如果没用，则返回环首部的节点
            entry = virtualNodes.firstEntry();
        }

        return entry.getValue();
    }


    private int getHash(Object key){
        return key.hashCode();
    }
}
